#include <QApplication>
#include <QMainWindow>
#include <QAction>
#include <QAction>
#include <QMenuBar>
#include <QWidget>
#include <QToolBar>
#include <QPlainTextEdit>
#include <QFileDialog>
#include <QDockWidget>
#include <QLabel>
#include <QTextEdit>
#include <QStatusBar>
#include <QGridLayout>
#include <QPrinter>
#include <QPainter>
#include <QDomNodeList>
#include <QDomNode>
#include <QBrush>

#include "MainWindow.h"
#include "renderarea.h"


//for standard c++
#include <iostream>
using namespace std;
//cout << "hello" << endl;

RenderArea::RenderArea(QWidget *parent)
  : QWidget(parent)
{
  //  shape = Polygon;
  //  antialiased = false;
  //  transformed = false;
  //  pixmap.load(":/images/qt-logo.png");
  setBackgroundRole(QPalette::Base);
  setAutoFillBackground(true);
}


void RenderArea::paintEvent(QPaintEvent *)
{
  QPrinter p;
  p.setPageSize(QPrinter::A4);
  p.setOrientation(QPrinter::Landscape);
  p.setPageMargins(0.0, 0.0, 0.0, 0.0, QPrinter::DevicePixel);
  p.setOutputFormat(QPrinter::PdfFormat);
  p.setOutputFileName("./test.pdf");
  
  int width = p.paperRect().width();
  int height = p.paperRect().height();
  cout << width << "x" << height << endl;

  //QPainter painter(this);
  QPainter painter(&p);
  //  painter.setPen(QColor(Qt::red));
  exit(1);
  //painter.begin(&p);
}

void RenderArea::printpage()
{
  QPrinter p;
  p.setPageSize(QPrinter::A4);
  p.setOrientation(QPrinter::Landscape);
  //p.setPageMargins(0.0, 0.0, 0.0, 0.0, QPrinter::DevicePixel);
  p.setPageMargins(19.0, 19.0, 19.0 , 19.0, QPrinter::DevicePixel);		//5mm
  p.setOutputFormat(QPrinter::PdfFormat);
  p.setOutputFileName("./test.pdf");
  
  //int width = p.paperRect().width();
  //int height = p.paperRect().height();
  int width = p.pageRect().width();
  int height = p.pageRect().height();
  cout << "paper size :" << p.paperRect().width() << "x" << p.paperRect().height() << endl;
  cout << "page size :" << width << "x" << height << endl;

  //QPainter painter(this);
  QPainter painter(&p);
  //  QPen pen;
  //  pen.setWidth(2);
  //  pen.setColor(Qt::red);
  //  painter.setPen(pen);

  test();	//read dict
  int startIndex = 0;
  
for(int page=0; page < 32; page++)
{
  startIndex = page * 16;

  if(page)
    p.newPage();	//not the first time to print

  for(int i=0;i<4;i++)
    {
      for(int j=0;j<4;j++)
	{
	  QRect rect(j*width/4, i*height/4, width/4, height/4);
	  QRect wordRect(j*width/4, i*height/4, width/4, height/4/2-3);
	  QRect phoneticRect(j*width/4, i*height/4+height/4/2+3, width/4, height/4/2);

	  painter.setPen(QPen(QBrush(QColor(195, 195, 195)), 1.5));
	  painter.drawRect(rect);
	  painter.setPen(QPen(QBrush(Qt::black), 1.0));

	  //painter.drawRect(wordRect);
	  //painter.drawRect(phoneticRect);
	  int idx = startIndex + i*4 + j;
	  painter.setFont(QFont("DejaVu Sans", 26));
	  if(dict.words[idx].phonetic=="")
	    {
	      painter.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, dict.words[idx].word);
	    }
	  else
	    {
	      painter.drawText(wordRect, Qt::AlignHCenter | Qt::AlignBottom | Qt::TextWordWrap, dict.words[idx].word);
	      painter.setFont(QFont("DejaVu Sans", 12));
	      painter.drawText(phoneticRect, Qt::AlignHCenter | Qt::AlignTop, dict.words[idx].phonetic);
	    }
	}
    }

  painter.setPen(QPen(QBrush(Qt::white), 3.0));
  painter.drawRect(QRect(0, 0, width-1, height-1));	//take out the border
  painter.setPen(QPen(QBrush(Qt::black), 1.0));
  
  p.newPage();
  painter.rotate(180.0);	//print mirror
  painter.setFont(QFont("文泉驿微米黑", 16));
  for(int i=0;i<4;i++)
    {
      for(int j=0;j<4;j++)
	{
	  //QRect rect(-j*width/4, -i*height/4, -width/4, -height/4);
	  QRect rect(-(j+1)*width/4, -(i+1)*height/4, width/4, height/4);

	  painter.setPen(QPen(QBrush(QColor(195, 195, 195)), 1.5));
	  painter.drawRect(rect);
	  painter.setPen(QPen(QBrush(Qt::black), 1.0));

	  int idx = startIndex + (3-i)*4 + j;
	  painter.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, dict.words[idx].trans);
	}
    }

  painter.setPen(QPen(QBrush(Qt::white), 3.0));
  painter.drawRect(QRect(0, 0, -(width), -(height)));	//take out the border
  painter.setPen(QPen(QBrush(Qt::black), 1.0));

  painter.resetTransform();
 }
 painter.end();
 
 cout << "ok" << endl;
 exit(1);
  //painter.begin(&p);
}




void RenderArea::test()
{
  dict.num = 0;
  QDomDocument doc("mydocument");
  QFile file("../reciteword/dict.xml");
  if(!file.open(QIODevice::ReadOnly))
    return;
  if(!doc.setContent(&file)){
    file.close();
    return;
  }
  file.close();
  QDomNodeList list = doc.firstChild().childNodes();	//<item>
  dict.num = 0;
  for(int i=0;i<list.length();i++){
    QDomNodeList itemList = list.item(i).childNodes();	//<word>,<trans>,<phonetic>,<tag>
    QString word = "", trans = "", phonetic = "", example = "";
    for(int j=0;j<itemList.length();j++)	//get word,trans,phonetic (ignore tag)
      {
	QDomNode node = itemList.item(j);
	//node.toElement().text();	//get the text of a node
	//node.nodeName()		//node name (QString)
	if(node.nodeName()=="word")
	  word = node.toElement().text();
	else if(node.nodeName()=="trans")
	  trans = node.toElement().text();
	else if(node.nodeName()=="phonetic")
	  phonetic = node.toElement().text();
	else if(node.nodeName()=="example")
	  example = node.toElement().text();
	//cout << qPrintable(node.nodeName()) << ":" << qPrintable(node.toElement().text()) << endl;
      }
    dict.words[dict.num].word = word;
    dict.words[dict.num].trans = trans;
    dict.words[dict.num].phonetic = phonetic;
    dict.words[dict.num].example = example;
    dict.words[dict.num].degree = DEFAULT_DEGREE;
    dict.num++;
    if(dict.num >= MAXNUM_OF_WORDS)	//get no more than this value
      break;
  }
}

MainWindow ::  MainWindow(QWidget *parent)
  : QMainWindow(parent)
{
  //QActions
  QAction *newAct= new QAction(tr("&New"), this);
  newAct->setShortcuts(QKeySequence::New);
  newAct->setStatusTip(tr("Create a new file"));
  connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
  //QAction *openAct = new QAction(QIcon(":/images/open.png"), tr("&Open"), this);		//where is the path of the images ??
  QAction *openAct = new QAction(QIcon("../images/open.png"), tr("&Open"), this);
  openAct->setShortcuts(QKeySequence::Open);
  openAct->setStatusTip(tr("open an existing file"));
  connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));
  QAction *quitAct = new QAction(tr("&Quit"), this);
  quitAct->setShortcuts(QKeySequence::Quit);
  quitAct->setStatusTip(tr("Quit"));
  connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));
  /*  QAction *aboutAct = new QAction(tr("&About"), this);
  aboutAct->setStatusTip(tr("show the app's about box"));
  connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
  */
  QAction *aboutQtAct = new QAction(tr("&About"), this);
  aboutQtAct->setStatusTip(tr("show the Qt library's about box"));
  connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

  //for test
  QAction *testAct = new QAction(tr("&Test"), this);
  //  quitAct->setShortcuts(QKeySequence(tr("Ctrl+X, Ctrl+S")));
  //quitAct->setShortcuts(QKeySequence(tr("Ctrl+T")));	??
  quitAct->setStatusTip(tr("test"));
  connect(testAct, SIGNAL(triggered()), this, SLOT(test()));


  //disable or enable some actions
  newAct->setEnabled(false);


  //create menubar and add qactions
  QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  fileMenu->addAction(newAct);
  fileMenu->addAction(openAct);
  fileMenu->addAction(quitAct);
  fileMenu->addSeparator();		//separator
  fileMenu->addAction(testAct);
  QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
  QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
  helpMenu->addAction(aboutQtAct);

  //create toolbar
  QToolBar *fileToolBar = addToolBar(tr("File"));
  fileToolBar->addAction(newAct);
  fileToolBar->addAction(openAct);
  fileToolBar->addAction(quitAct);
  fileToolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
  addToolBar(Qt::TopToolBarArea, fileToolBar);


  //
  /*  QLabel *label = new QLabel(tr("hello"));

  //create QDockWidget
  QDockWidget *dockWidget = new QDockWidget(tr("Dock Widget"), this);
  dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
  dockWidget->setWidget(label);
  addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
  */

  //create the centeral widget
  //QWidget *centralWidget = new QWidget(this);
  //setCentralWidget(centralWidget);
  //  textEdit = new QPlainTextEdit;
  //  setCentralWidget(textEdit);

  QLabel *nameLabel = new QLabel(tr("Name:"));
  nameLine = new QLineEdit;
  QLabel *contentLabel = new QLabel(tr("Content"));
  contentText = new QTextEdit;
  
  QGridLayout *mainLayout = new QGridLayout;
  mainLayout->addWidget(nameLabel, 0, 0);
  mainLayout->addWidget(nameLine, 0, 1);
  mainLayout->addWidget(contentLabel, 1, 0, Qt::AlignTop);
  mainLayout->addWidget(contentText, 1, 1);
  setLayout(mainLayout);


  //QMessageBox::about(this, ),

  //status bar ????
  statusBar()->showMessage(tr("ready"));
  //statusBar()->showMessage(tr("ready"), 2000);

  //window title
  //setWindowTitle(tr("Qt4 template"));
}

void MainWindow::openFile()
{
  //  QString fileName = QFileDialog::getOpenFileName(this);
  //  if(!fileName.isEmpty())
  //    cout << "not empty " << endl;


  QPainter painter(this);
  painter.setPen(Qt::blue);
  painter.setFont(QFont("Arial", 30));
  painter.drawText(rect(), Qt::AlignCenter, "Qt");
  


  QPrinter p;
  p.setPageSize(QPrinter::A4);
  p.setOutputFormat(QPrinter::PdfFormat);
  p.setOutputFileName("./test.pdf");
  
  //  QPainter painter;
  QTextDocument doc;
  doc.setHtml("\
<table style='width:100;height:100;border:1px solid #ff00ff;'> \
<tr><td>hello</td>world<td><td>hello</td>world<td></tr> \
<tr><td>hello</td>world<td><td>hello</td>world<td></tr> ");
  doc.print(&p);
  //doc.end();
}

void MainWindow::newFile()
{
  QString fileName = QFileDialog::getOpenFileName(this);
  /*  if(!fileName.isEmpty())
    cout << "hello" << endl;
  */
}

void MainWindow::test()
{
  QString fileName = QFileDialog::getOpenFileName(this);
}



int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  app.setOrganizationName("kang@xmu");
  app.setApplicationName("Qt4 Application Template");
  //app.setWindowIcon();
  //app.setMainWidget(&mw);
  //  MainWindow mw;
  //  mw.resize(640,480);
  //  mw.show();
  //  mw.setWindowTitle(QApplication::translate("toplevel", "top-level widget"));
  RenderArea ra;
  ra.printpage();
  //ra.show();
  return app.exec();
}
